package com.yangye.pidoublename.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yangye.pidoublename.service.DoubleNameService;
import com.yangye.pidoublename.service.ProvinceEnum;
import com.yangye.pidoublename.vo.DoubleNameVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/**
 * @author yangye
 * @date 2019/9/20
 */
@Service
public class ShangHaiServiceImpl implements DoubleNameService {

	@Autowired
	private RestTemplate restTemplate;

	private final String QUERY_URL = "https://shanghaicity.openservice.kankanews.com/citizen/repeat?name=";
	@Override
	public DoubleNameVo findByName(String name) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Mobile Safari/537.36");
		HttpEntity request = new HttpEntity<>(headers);
		ResponseEntity<JSONObject> result = restTemplate.exchange(QUERY_URL + name, HttpMethod.GET, request, JSONObject.class);
		Integer total = result.getBody().getInteger("count");
		DoubleNameVo doubleNameVo = new DoubleNameVo();
		doubleNameVo.setProvince(ProvinceEnum.SHANGHAI.getName());
		doubleNameVo.setName(name);
		doubleNameVo.setTotal(total);
		return doubleNameVo;
	}
}
